package org.tulkas.data;

import java.io.FileReader;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.tulkas.base.ITulkasApplicationContext;
import org.tulkas.util.FileUtil;

import com.mongodb.DB;
import com.mongodb.Mongo;
import com.mongodb.MongoException;

/**
 * @author <a href="mailto:tulkas.web@gmail.com">Tulkas</a>
 *
 */
@Service
public class AppDataManager {
	private static Logger logger = LoggerFactory
			.getLogger(AppDataManager.class);
	public static final String DATA_CONFIG_FILE = "appData.properties";

	private boolean avaliable = false;
	private MongoConnector connector = null;
	private Exception connectionError = null;

	@Autowired
	private ITulkasApplicationContext appContext;

	public boolean isAvaliable() {
		return avaliable;
	}

	public void init() {
		avaliable = false;
		connectionError = null;
		Properties props = new Properties();
		String rootPath = appContext.getRootPath();
		String file = rootPath + "/" + DATA_CONFIG_FILE;
		FileReader fr = null;
		try {
			fr = new FileReader(file);
			props.load(fr);
		} catch (IOException e) {
			logger.info("Can't load data connection configuration file ["
					+ file + "]");
			return;
		} finally {
			FileUtil.muteClose(fr);
		}

		try {
			connector = new MongoConnector(props);
			connector.getDB().getCollectionNames();
		} catch (Exception e1) {
			logger.error("Error connecting to mongo server", e1);
			connectionError = e1;
			return;
		}

		logger.info("Initializing mongo connector successfully. ["
				+ connector.toString() + "]");
		avaliable = true;
	}

	public DB getDB() {
		if (avaliable) {
			return connector.getDB();
		} else {
			return null;
		}
	}

	public Mongo getMongo() {
		if (avaliable) {
			return connector.getMongo();
		} else {
			return null;
		}
	}

	public Exception getConnectionError() {
		return connectionError;
	}

}
